interface Props {
	isView?: boolean;
}

import { ProForm, ProFormDependency, ProFormInstance, ProFormList, ProFormText } from "@ant-design/pro-components";
import styles from "./index.module.less";
import { Fragment, useEffect, useRef, useState } from "react";
import { Space, Image, Button, Affix, Flex, message } from "antd";
import Upload from "@/components/Upload";
import { CheckCircleOutlined } from "@ant-design/icons";
import { MAIN_PRIMARY_COLOR } from "@/enums";
import { useRequest } from "ahooks";
import { addBanner, getBannerList } from "@/api/modules/course";
import Loading from "@/components/Loading";
import { isEmpty, map, join, omit } from "lodash";
import { RESULT_CODES } from "@/api/helper/ResultCode";

export default (props: Props) => {
	const formRef = useRef<ProFormInstance | undefined>();
	const { data, loading, run } = useRequest(getBannerList);
	const [isEdit, setIsEdit] = useState(false);
	const { loading: editLoading, runAsync } = useRequest(addBanner, { manual: true });

	useEffect(() => {
		if (!isEmpty(data?.data)) {
			formRef.current?.setFieldsValue({
				banners: map(data?.data, i => ({
					...i,
					imgUpload: i?.course_banner_pic
				}))
			});
		}
	}, [data]);

	const handleBack = () => {
		setIsEdit(false);
		run();
	};

	const handleSubmit = () => {
		formRef.current?.validateFieldsReturnFormatValue?.().then(values => {
			const banners = map(values?.banners, i => omit(i, ["imgUpload"]));
			runAsync({ banners }).then(res => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					message.success("保存成功");
					setIsEdit(false);
				}
			});
		});
	};

	return (
		<Loading isHeight100={true} loading={loading}>
			<div className={styles.container}>
				<div className={styles.msg}>建议尺寸：1035*582px，小于5M的JPG/PNG格式图片</div>
				<ProForm disabled={!isEdit} className={styles.form} submitter={false} formRef={formRef} layout="horizontal">
					<ProFormList
						name="banners"
						deleteIconProps={false}
						copyIconProps={false}
						creatorButtonProps={isEdit ? { creatorButtonText: "增加Banner" } : false}
						max={4}
					>
						{(meta, index, action, count) => {
							const rowData = action.getCurrentRowData();
							return (
								<>
									<Space className={styles.space} size={20} align="center">
										<ProFormDependency name={["course_banner_pic"]}>
											{({ course_banner_pic }) => {
												formRef.current?.setFieldValue(["banners", index, "imgUpload"], course_banner_pic);
												return (
													<ProForm.Item
														name="imgUpload"
														label={`${index > 8 ? "" : "0"}${index + 1}`}
														rules={[{ required: isEdit, message: "" }]}
													>
														<Image preview={false} width={265} height={150} src={course_banner_pic} />
													</ProForm.Item>
												);
											}}
										</ProFormDependency>
										{isEdit && (
											<>
												<ProForm.Item name="course_banner_pic" noStyle>
													<Upload
														isShowUploadBtn={true}
														listType="text"
														uploadNode={<a>{Boolean(rowData?.course_banner_pic) ? "修改" : "上传"}</a>}
														showUploadListConfig={false}
														resFormat={res => join(map(res, "url"), ",")}
														maxSize={5}
													/>
												</ProForm.Item>

												<a style={{ color: "#EE3C36" }} onClick={() => action.remove(index)}>
													删除
												</a>
											</>
										)}
									</Space>
									<ProFormText label="课程ID" rules={[{ required: isEdit, message: "" }]} name="course_banner_url" />
								</>
							);
						}}
					</ProFormList>
				</ProForm>
				<Affix offsetBottom={0}>
					<Flex justify="center" className={styles.btns}>
						<Space size={10}>
							{isEdit ? (
								<>
									<Button ghost type="primary" onClick={() => handleBack()}>
										取消
									</Button>
									<Button loading={editLoading} ghost type="primary" onClick={() => handleSubmit()}>
										保存发布
									</Button>

									{/* <Space size={10}>
										<CheckCircleOutlined style={{ color: MAIN_PRIMARY_COLOR }} />
										<span style={{ color: "#000" }}>最后保存于2024-05-26</span>
									</Space> */}
								</>
							) : (
								<Button onClick={() => setIsEdit(true)} type="primary">
									编辑
								</Button>
							)}
						</Space>
					</Flex>
				</Affix>
			</div>
		</Loading>
	);
};
